package middleware

import (
	"git.mycaigou.com/gfyx/common/authorize"
	"git.myscrm.cn/golang/common/ykerrcode"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
	"net/http"
)


func ErrResponse(ctx *gin.Context, errorCode int, msg string) {
	result := gin.H{
		"success":    false,
		"message":    msg,
		"error_code": errorCode,
		"data":       nil,
	}

	ctx.JSON(http.StatusOK, result)
	ctx.Abort()
}

func ServiceAuthorize() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		authorizationStr := ctx.Request.Header.Get("authorization")
		err := authorize.JwtServiceAuthorize(authorizationStr, func(appid string) (signKey string) {
			//return "test666"
			return stark.Configer.(stark.ApolloConfigerIface).GetStringValue("Auth."+appid+".AppKey", "")
		})
		if err != nil {
			stark.Logger.Errorf(ctx, "鉴权失败。authorization:%s err:%v", authorizationStr, err)
			ErrResponse(ctx, ykerrcode.ACCESS_DENIED, "鉴权失败：" + err.Error())
			return
		}
		ctx.Next()
	}
}

